package com.linphone.demo;

import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.linphone.mediastream.Log;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity{
	
	private TextView txt_name;
	private TextView txt_nickname;
	private TextView txt_password;
	private TextView txt_result;
	private EditText edit_name;
	private EditText edit_nickname;
	private EditText edit_password;
	private Button btn_register;
	private AESCrypt mAESCrypt;
	private final static String URL = "https://sandbox.baby-kingdom.com/buddieApp/insert_user.php";
	
	private final Activity activity = this;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_register);
		
		initView();
		try {
			mAESCrypt = new AESCrypt();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initView() {
		txt_name = (TextView ) findViewById(R.id.txt_name);
		txt_nickname = (TextView) findViewById(R.id.txt_nickname);
		txt_password = (TextView ) findViewById(R.id.txt_password);
		txt_result = (TextView) findViewById(R.id.txt_result);
		edit_name = (EditText) findViewById(R.id.edit_name);
		edit_nickname = (EditText) findViewById(R.id.edit_nickname);
		edit_password = (EditText) findViewById(R.id.edit_password);
		btn_register = (Button) findViewById(R.id.btn_register);
		
		btn_register.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String username = edit_name.getText().toString().trim();
				if(username == null || "".equals(username)){
					Toast.makeText(activity, "username is Empty!", Toast.LENGTH_SHORT).show();
					return ;
				}
				String nickname = edit_name.getText().toString().trim();
				if(nickname == null || nickname.equals("")){
					Toast.makeText(activity, "nickname is Empty!", Toast.LENGTH_SHORT).show();
					return;
				}
				
				String password = edit_password.getText().toString().trim();
				if(password == null || password.equals("")){
					password = "88888888";
				}
				String secret = "";
				try {
					secret = mAESCrypt.encrypt(username+"+"+nickname);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(secret.equals("")){
					Toast.makeText(activity, "AESCrypt is Empty!", Toast.LENGTH_SHORT).show();
					return;
				}
				
				post(username, nickname, password, secret);
			}
		});
	}
	
	public class AESCrypt {
	    private final Cipher cipher;
	    private final SecretKeySpec key;
	    private AlgorithmParameterSpec spec;
	    public static final String SEED_16_CHARACTER = "bk123!longkey!";
	    public AESCrypt() throws Exception {
	        // hash password with SHA-256 and crop the output to 128-bit for key
	        MessageDigest digest = MessageDigest.getInstance("SHA-256");
	        digest.update(SEED_16_CHARACTER.getBytes("UTF-8"));
	        byte[] keyBytes = new byte[32];
	        System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
	        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
	        key = new SecretKeySpec(keyBytes, "AES");
	        spec = getIV();
	    }
	    public AlgorithmParameterSpec getIV() {
	        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
	        IvParameterSpec ivParameterSpec;
	        ivParameterSpec = new IvParameterSpec(iv);
	        return ivParameterSpec;
	    }
	    public String encrypt(String plainText) throws Exception {
	        cipher.init(Cipher.ENCRYPT_MODE, key, spec);
	        byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
	        String encryptedText = new String(Base64.encode(encrypted,
	                Base64.DEFAULT), "UTF-8");
	        return encryptedText;
	    }
	    public String decrypt(String cryptedText) throws Exception {
	        cipher.init(Cipher.DECRYPT_MODE, key, spec);
	        byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT);
	        byte[] decrypted = cipher.doFinal(bytes);
	        String decryptedText = new String(decrypted, "UTF-8");
	        return decryptedText;
	    }
	}
	
	private void post(final String username , final String nickname , final String password , final String secret){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

					DefaultHttpClient client = new DefaultHttpClient();

					SchemeRegistry registry = new SchemeRegistry();
					SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
					socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
					registry.register(new Scheme("https", socketFactory, 443));
					SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
					DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

					// Set verifier     
					HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
					
					HttpPost httpPost = new HttpPost(URL);
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("username", username));
					params.add(new BasicNameValuePair("nickname", nickname));
					params.add(new BasicNameValuePair("password", password));
					params.add(new BasicNameValuePair("secret", secret));
					Log.e("username -> "+username+" nickname-> "+nickname+" password -> "+ password+" secret -> "+ secret);
					HttpEntity entity = new UrlEncodedFormEntity(params);
					httpPost.setEntity(entity);
					HttpResponse response = httpClient.execute(httpPost);
					Log.e(""+response.getStatusLine());
					if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
						Message message = new Message();
						message.what = 1;
						message.obj = EntityUtils.toString(response.getEntity());
						mHandler.sendMessage(message);
					}else{
						mHandler.sendEmptyMessage(0);
					}
					
					return ;
				} catch (Exception e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(0);
			}
		}).start();
	}
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				try {
					String result = (String)msg.obj;
					JSONObject jsonObject = new JSONObject(result);
					txt_result.setText(jsonObject.getString("message"));
				} catch (Exception e) {
					e.printStackTrace();
					txt_result.setText("register error !");
				}
				
				break;

			case 0:
				txt_result.setText("register error !");
				break;
			default:
				break;
			}
		};
	};
	
}
